package 网络编程.客户端与服务器的请求与响应.UDP数据报.服务器;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer {
    public static void main(String[] args) throws IOException {
        UdpEchoServer up = new UdpEchoServer(9099);
        up.start();
    }
    //先创建一个socket对象
    private DatagramSocket socket = null;
    //构造方法传入端口号
    public UdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }
    //服务器启动方法
    public void start() throws IOException {

        System.out.println("服务器启动");
        while(true){
            //1.读取请求解析 String 拿到数据报
            DatagramPacket requestPacket = new DatagramPacket(new byte[2048],2048);
            socket.receive(requestPacket);
            String request =new String(requestPacket.getData(),0,requestPacket.getLength());
            //2.根据请求 做出响应
            String response = process(request);
            //3.响应返回给客户端
            DatagramPacket responsePacket = new DatagramPacket(response.getBytes(),0,response.getBytes().length,
                    requestPacket.getSocketAddress());
            System.out.printf("[%s:%d] request = %s ,response = %s\n",requestPacket.getAddress(),
                    responsePacket.getPort(),request,response);
            socket.send(responsePacket);

        }

    }
    public String process(String request){
        return  request;
    }
}
